<template>
  <view class="contact-list">
    <view class="section-title" @click="toggleContactList">
      <text class="title-text">联系人</text>
      <text class="toggle-icon">{{ isExpanded ? '︽' : '︾' }}</text>
    </view>
    <view v-show="isExpanded">
      <!-- 搜索框 -->
      <view class="search-container">
        <input 
          class="search-input" 
          placeholder="搜索联系人..." 
          v-model="searchKeyword"
          @input="handleSearch"
        />
        <text class="search-icon">🔍</text>
      </view>
      <scroll-view 
        class="contact-scroll-container"
        scroll-y="true"
        :refresher-enabled="true"
        :refresher-triggered="refreshing"
        @refresherrefresh="onRefresh"
      >
        <view class="contact-items">
          <view 
            v-for="contact in filteredContacts" 
            :key="contact.user_id" 
            class="contact-item"
            @click="handleContactClick(contact)"
          >
            <image 
              class="contact-avatar" 
              :src="contact.avatar || defaultAvatar" 
              mode="aspectFill"
            ></image>
            <view class="contact-info">
              <text class="contact-name">{{ contact.name }}</text>
              <text class="contact-account">@{{ contact.account || contact.username }}</text>
            </view>
          </view>
          <view v-if="filteredContacts.length === 0" class="no-results">
            <text class="no-results-text">未找到相关联系人</text>
          </view>
        </view>
      </scroll-view>
    </view>
    
    <!-- 聊天窗口 -->
    <view class="chat-window-overlay" v-if="showChatWindow">
      <ChatWindow 
        :other-user="selectedContact"
        :chat-id="chatId"
        @close="closeChatWindow"
      />
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import { getUserList } from '@/api/user/index'
import { getUserInfo } from '@/utils/index'
import { createPrivateChat } from '@/api/user/privateChat'
import ChatWindow from '@/components/ChatWindow.vue'

// 定义联系人数据类型
interface Contact {
  user_id: number
  name: string
  account?: string
  username?: string
  avatar?: string
}

// 控制联系人列表展开/收起
const isExpanded = ref(true)

// 联系人列表
const contacts = ref<Contact[]>([])

// 搜索关键词
const searchKeyword = ref('')

// 默认头像
const defaultAvatar = '/static/logo.png'

// 聊天窗口相关
const showChatWindow = ref(false)
const selectedContact = ref<Contact>({} as Contact)
const chatId = ref<number | null>(null)

// 下拉刷新状态
const refreshing = ref(false)

// 切换联系人列表显示状态
const toggleContactList = () => {
  isExpanded.value = !isExpanded.value
  // 当展开联系人列表时，刷新数据
  if (isExpanded.value) {
    fetchContacts()
  }
}

// 计算属性：过滤后的联系人列表
const filteredContacts = computed(() => {
  if (!searchKeyword.value.trim()) {
    return contacts.value
  }
  
  const keyword = searchKeyword.value.toLowerCase().trim()
  return contacts.value.filter(contact => {
    return (
      (contact.name && contact.name.toLowerCase().includes(keyword)) ||
      (contact.account && contact.account.toLowerCase().includes(keyword)) ||
      (contact.username && contact.username.toLowerCase().includes(keyword))
    )
  })
})

// 获取联系人列表
const fetchContacts = async () => {
  try {
    const res: any = await getUserList()
    if (res.code === 200) {
      // 获取当前用户信息
      const currentUser = getUserInfo()
      const currentUserId = currentUser ? currentUser.user_id : null
      
      // 过滤掉当前用户
      contacts.value = res.data
        .filter((item: any) => item.user_id !== currentUserId)
        .map((item: any) => ({
          user_id: item.user_id,
          name: item.name,
          account: item.account,
          username: item.username,
          avatar: item.avatar
        }))
    } else {
      throw new Error(res.message || '获取联系人失败')
    }
  } catch (error) {
    console.error('获取联系人列表失败:', error)
  } finally {
    // 停止下拉刷新状态
    refreshing.value = false
  }
}

// 下拉刷新处理
const onRefresh = async () => {
  if (refreshing.value) return
  refreshing.value = true
  await fetchContacts()
}

// 处理搜索
const handleSearch = () => {
  // 搜索逻辑已经在 computed 属性中实现
}

// 处理联系人点击事件
const handleContactClick = async (contact: Contact) => {
  try {
    // 创建私聊会话
    const res: any = await createPrivateChat({ other_user_id: contact.user_id })
    if (res.code === 200) {
      // 打开聊天窗口
      selectedContact.value = contact
      chatId.value = res.data.chat_id || null
      showChatWindow.value = true
    } else {
      throw new Error(res.message || '创建聊天失败')
    }
  } catch (error) {
    console.error('创建私聊会话失败:', error)
  }
}

// 关闭聊天窗口
const closeChatWindow = () => {
  showChatWindow.value = false
  selectedContact.value = {} as Contact
  chatId.value = null
}

// 组件挂载时获取联系人列表
onMounted(() => {
  fetchContacts()
})
</script>

<style scoped>
.contact-list {
  background: #ffffff;
  border-radius: 24rpx;
  margin: 30rpx;
  box-shadow: 0 12rpx 30rpx rgba(0, 0, 0, 0.06);
  padding: 30rpx;
  position: relative;
}

.section-title {
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
}

.title-text {
  font-size: 32rpx;
  font-weight: 600;
  color: #2c3e50;
  position: relative;
  padding-left: 16rpx;
}

.title-text::before {
  content: "";
  position: absolute;
  left: 0;
  top: 5rpx;
  width: 8rpx;
  height: 32rpx;
  background: linear-gradient(to bottom, #007aff, #00c874);
  border-radius: 4rpx;
}

.toggle-icon {
  font-size: 32rpx;
  color: #7f8c8d;
  transition: transform 0.3s ease;
}

.search-container {
  position: relative;
  margin-bottom: 30rpx;
}

.search-input {
  width: 100%;
  height: 70rpx;
  padding: 0 20rpx 0 60rpx;
  background-color: #f8f9fa;
  border-radius: 35rpx;
  font-size: 28rpx;
  border: 2rpx solid #eee;
  box-sizing: border-box;
}

.search-icon {
  position: absolute;
  left: 25rpx;
  top: 50%;
  transform: translateY(-50%);
  font-size: 28rpx;
  color: #7f8c8d;
}

.contact-scroll-container {
  height: 600rpx;
}

.contact-items {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
  padding: 20rpx 0;
}

.contact-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  border-radius: 16rpx;
  transition: all 0.3s ease;
}

.contact-item:hover {
  background-color: #f8f9fa;
}

.contact-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 20rpx;
  border: 2rpx solid #eee;
}

.contact-info {
  display: flex;
  flex-direction: column;
}

.contact-name {
  font-size: 28rpx;
  color: #2c3e50;
  margin-bottom: 6rpx;
  font-weight: 500;
}

.contact-account {
  font-size: 24rpx;
  color: #7f8c8d;
}

.no-results {
  text-align: center;
  padding: 40rpx 0;
}

.no-results-text {
  font-size: 28rpx;
  color: #95a5a6;
}

.chat-window-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>